//
//  HZPeiziBuySellTopView.m
//  Stock_Stategy
//
//  Created by MayerF on 2017/12/14.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "HZPeiziBuySellTopView.h"
#import "MYCustomLeftRightBtn.h"
#import "HZLandscapeWuDangView.h"

@interface HZPeiziBuySellTopView()<UITextFieldDelegate>
@property (nonatomic, strong)UIView *pLeftView;
@property (nonatomic, strong)UITextField *pCodeTextField;
@property (nonatomic, strong)UITextField *pCodeUpTextField;
@property (nonatomic, strong)UILabel *pNameLabel;
@property (nonatomic, strong)MYCustomLeftRightBtn *pTradeType;
@property (nonatomic, strong)UIButton *pMinusPriceBtn;
@property (nonatomic, strong)UIButton *pPlusPriceBtn;
@property (nonatomic, strong)UITextField *pPriceTextField;
@property (nonatomic, strong)UILabel *pMaxPriceLabel;
@property (nonatomic, strong)UILabel *pMinPriceLabel;
@property (nonatomic, strong)UIButton *pMinusNumBtn;
@property (nonatomic, strong)UIButton *pPlusNumBtn;
@property (nonatomic, strong)UITextField *pNumTextField;
@property (nonatomic, strong)UIButton *pTradeBtn;
@property (nonatomic, strong)HZLandscapeWuDangView *pWudangView;

@property (nonatomic, strong)UITextField *pTradeTypeBg;

@property (nonatomic, strong)HZMinPriceModel *pTempData;
@property (nonatomic, strong)HZPeiziAccountMoneyModel *moneyData;
@property (nonatomic, strong)NSArray *pStockListData;
@property (nonatomic, assign)BOOL isLoadingData;//是否已经加载到数据
@end

@implementation HZPeiziBuySellTopView

#pragma mark -
#pragma mark 生命周期
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self initCommon];
        [self initConstraints];
    }
    return self;
}
- (void)initCommon
{
    _pLeftView = [UIView new];
    _pCodeTextField = [UITextField new];
    _pTradeType = [MYCustomLeftRightBtn new];
    _pMinusPriceBtn = [UIButton new];
    _pPlusPriceBtn = [UIButton new];
    _pPriceTextField = [UITextField new];
    _pMaxPriceLabel = [UILabel new];
    _pMinPriceLabel = [UILabel new];
    _pMinusNumBtn = [UIButton new];
    _pPlusNumBtn = [UIButton new];
    _pNumTextField = [UITextField new];
    _pTradeBtn = [UIButton new];
    _pWudangView = [HZLandscapeWuDangView new];
    _pCodeUpTextField = [UITextField new];
    _pNameLabel = [UILabel new];
    _pTradeTypeBg = [UITextField new];
    _pTradeTypeBg.enabled = NO;
    
    _pCodeTextField.placeholder = @"股票代码";
    _pPriceTextField.placeholder = @"委托价格";
    _pNumTextField.placeholder = @"委托数量";
    _pMaxPriceLabel.text = @"涨停";
    _pMinPriceLabel.text = @"跌停";
    [_pTradeBtn setTitle:@"买入" forState:UIControlStateNormal];
    
    [_pTradeType setTitle:@"申报方式" forState:UIControlStateNormal];
    [_pTradeType setTitle:@"限价" forState:UIControlStateSelected];
    [_pTradeType setTitleColor:kMYHexToRGB(0xd3d3d3, 1) forState:UIControlStateNormal];
    [_pTradeType setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [_pTradeType setImage:[UIImage imageNamed:@"mark_down"] forState:UIControlStateSelected];
    
    _pCodeTextField.textAlignment = _pPriceTextField.textAlignment =
    _pNumTextField.textAlignment = NSTextAlignmentCenter;
    _pCodeTextField.borderStyle = _pPriceTextField.borderStyle =
    _pNumTextField.borderStyle = UITextBorderStyleRoundedRect;
    _pCodeTextField.font = _pPriceTextField.font =
    _pNumTextField.font = [UIFont systemFontOfSize:14];
    _pTradeType.titleLabel.font = [UIFont systemFontOfSize:14];
    _pMaxPriceLabel.font = _pMinPriceLabel.font = [UIFont systemFontOfSize:13];
    _pTradeBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    _pCodeUpTextField.textAlignment = NSTextAlignmentRight;
    _pNameLabel.textAlignment = NSTextAlignmentLeft;
    _pCodeUpTextField.font = _pNameLabel.font = [UIFont systemFontOfSize:14];
    
    _pCodeTextField.delegate = self;
    _pCodeUpTextField.delegate = self;
    
    _pMinusPriceBtn.tag = 1;
    _pPlusPriceBtn.tag = 2;
    _pMinusNumBtn.tag = 3;
    _pPlusNumBtn.tag = 4;
    [_pMinusPriceBtn addTarget:self action:@selector(adjustOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pPlusPriceBtn addTarget:self action:@selector(adjustOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pMinusNumBtn addTarget:self action:@selector(adjustOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pPlusNumBtn addTarget:self action:@selector(adjustOnClick:) forControlEvents:UIControlEventTouchUpInside];
    [_pTradeType addTarget:self action:@selector(tradeTypeOnClick) forControlEvents:UIControlEventTouchUpInside];
    [_pTradeBtn addTarget:self action:@selector(tradeBtnOnClick) forControlEvents:UIControlEventTouchUpInside];
    
    _pTradeTypeBg.borderStyle = UITextBorderStyleRoundedRect;
    _pCodeTextField.keyboardType = _pCodeUpTextField.keyboardType = _pNumTextField.keyboardType = UIKeyboardTypeNumberPad;
    _pPriceTextField.keyboardType = UIKeyboardTypeDecimalPad;
    _pTradeType.backgroundColor = [UIColor whiteColor];
    _pTradeTypeBg.backgroundColor = [UIColor whiteColor];
    _pTradeBtn.layer.cornerRadius = 3;
    _pTradeBtn.layer.masksToBounds = YES;
    
    [_pWudangView resetFont:14];
    [_pWudangView setVerticalLineColor:kMYHexToRGB(0xe4e3e6, 1)];
    
    _pCodeUpTextField.hidden = _pNameLabel.hidden = YES;
    _pMinusNumBtn.enabled = _pPlusNumBtn.enabled = NO;
    _pMinusPriceBtn.enabled = _pPlusPriceBtn.enabled = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange:) name:UITextFieldTextDidChangeNotification object:_pCodeTextField];
}
- (void)initConstraints
{
    [self addSubview:_pLeftView];
    [_pLeftView addSubview:_pCodeTextField];
    [_pLeftView addSubview:_pTradeTypeBg];
    [_pLeftView addSubview:_pMinusPriceBtn];
    [_pLeftView addSubview:_pPlusPriceBtn];
    [_pLeftView addSubview:_pPriceTextField];
    [_pLeftView addSubview:_pMaxPriceLabel];
    [_pLeftView addSubview:_pMinPriceLabel];
    [_pLeftView addSubview:_pMinusNumBtn];
    [_pLeftView addSubview:_pPlusNumBtn];
    [_pLeftView addSubview:_pNumTextField];
    [_pLeftView addSubview:_pTradeBtn];
    [_pCodeTextField addSubview:_pCodeUpTextField];
    [_pCodeTextField addSubview:_pNameLabel];
    [_pLeftView addSubview:_pTradeType];
    
    [self addSubview:_pWudangView];
    
    [_pLeftView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(self);
        make.left.mas_equalTo(self).offset(10);
        make.right.mas_equalTo(_pWudangView.mas_left).offset(-10);
//        make.width.mas_equalTo(200);
    }];
    [_pCodeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(_pLeftView).offset(10);
        make.left.right.mas_equalTo(_pLeftView);
        make.bottom.mas_equalTo(_pTradeTypeBg.mas_top).offset(-10);
    }];
    [_pCodeUpTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(_pCodeTextField);
        make.left.mas_equalTo(_pCodeTextField);
        make.right.mas_equalTo(_pNameLabel.mas_left).offset(-10);
    }];
    [_pNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.right.mas_equalTo(_pCodeTextField);
        make.width.mas_equalTo(_pCodeUpTextField);
    }];
    [_pTradeTypeBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(_pLeftView);
        make.bottom.mas_equalTo(_pPriceTextField.mas_top).offset(-10);
    }];
    [_pMinusPriceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(_pPriceTextField);
        make.left.mas_equalTo(_pLeftView);
        make.right.mas_equalTo(_pPriceTextField.mas_left).offset(-5);
    }];
    [_pPriceTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(_pPlusPriceBtn.mas_left).offset(-5);
        make.bottom.mas_equalTo(_pMaxPriceLabel.mas_top);
    }];
    [_pPlusPriceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(_pPriceTextField);
        make.right.mas_equalTo(_pLeftView);
    }];
    [_pMaxPriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_pLeftView);
        make.right.mas_equalTo(_pMinPriceLabel.mas_left);
        make.bottom.mas_equalTo(_pNumTextField.mas_top);
    }];
    [_pMinPriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(_pLeftView);
        make.top.bottom.mas_equalTo(_pMaxPriceLabel);
        make.width.mas_equalTo(_pMaxPriceLabel);
    }];
    
    [_pMinusNumBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(_pNumTextField);
        make.left.mas_equalTo(_pLeftView);
        make.right.mas_equalTo(_pNumTextField.mas_left).offset(-5);
    }];
    [_pNumTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(_pPlusNumBtn.mas_left).offset(-5);
        make.bottom.mas_equalTo(_pTradeBtn.mas_top).offset(-10);
    }];
    [_pPlusNumBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.mas_equalTo(_pNumTextField);
        make.right.mas_equalTo(_pLeftView);
        make.width.mas_equalTo(_pPriceTextField.mas_height);
        make.width.mas_equalTo(@[_pMinusNumBtn, _pPlusPriceBtn, _pMinusPriceBtn]);
    }];
    [_pTradeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(_pLeftView);
        make.bottom.mas_equalTo(_pLeftView).offset(-10);
        make.height.mas_equalTo(@[_pNumTextField, _pPriceTextField, _pMaxPriceLabel, _pTradeTypeBg, _pCodeTextField]);
    }];
    
    [_pWudangView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self).offset(10);
        make.right.mas_equalTo(self).offset(-10);
        make.bottom.mas_equalTo(self).offset(-10);
        make.width.mas_equalTo(120);
    }];
    [_pTradeType mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_pTradeTypeBg).offset(5);
        make.right.mas_equalTo(_pTradeTypeBg).offset(-5);
        make.top.mas_equalTo(_pTradeTypeBg).offset(5);
        make.bottom.mas_equalTo(_pTradeTypeBg).offset(-5);
    }];
}

- (void)updateMoneyData:(NSString *)num
{
    NSString *temp = num;
    if (_nTradeType == kTrade_Buy_Type) {
        temp = [NSString stringWithFormat:@"最大可买%@",num];
    }else {
        temp = [NSString stringWithFormat:@"最大可卖%@",num];
    }
    _pNumTextField.placeholder = temp;
}
- (void)updateAccountData:(NSArray<HZPeiziTradeStockListModel *> *)data
{
    _pStockListData = data;
}
- (void)updateTopData:(HZMinPriceModel *)data
{
    if (!data) { return;}
    if (_isLoadingData) {
        [_pWudangView updateNewData:data];
        return;
    }
    _pTempData = data;
    _pMinusNumBtn.enabled = _pPlusNumBtn.enabled = YES;
    _pMinusPriceBtn.enabled = _pPlusPriceBtn.enabled = YES;
    
    _pCodeUpTextField.hidden = _pNameLabel.hidden = NO;
    _pCodeTextField.text = @" ";
    _pCodeUpTextField.text = data.model_code;
    _pNameLabel.text = data.model_name;
    _pTradeType.selected = YES;
    _pMaxPriceLabel.text = [NSString stringWithFormat:@"涨停  %@", data.model_zhangTing];
    _pMinPriceLabel.text = [NSString stringWithFormat:@"跌停  %@", data.model_dieTing];
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:_pMaxPriceLabel.text];
    [attStr addAttribute:NSForegroundColorAttributeName value:kREDColor range:NSMakeRange(2, attStr.length-2)];
    _pMaxPriceLabel.attributedText = attStr;
    attStr = [[NSMutableAttributedString alloc] initWithString:_pMinPriceLabel.text];
    [attStr addAttribute:NSForegroundColorAttributeName value:kGREENColor range:NSMakeRange(2, attStr.length-2)];
    _pMinPriceLabel.attributedText = attStr;
    
    NSArray *wudang = data.model_wuDangArray;
    if (_nTradeType == kTrade_Buy_Type && wudang.count > 4) {
        HZWuDangModel *model = wudang[4];
        _pPriceTextField.text = model.model_price;
    }else if (_nTradeType == kTrade_Sell_Type && wudang.count > 5) {
        HZWuDangModel *model = wudang[5];
        _pPriceTextField.text = model.model_price;
    }
    
    [_pWudangView updateNewData:data];
    _isLoadingData = YES;
}

- (void)setNTradeType:(kTradeType)nTradeType
{
    _nTradeType = nTradeType;
    if (nTradeType == kTrade_Buy_Type) {
        [_pTradeBtn setTitle:@"买入" forState:UIControlStateNormal];
        _pTradeBtn.backgroundColor = kREDColor;
        [_pMinusPriceBtn setImage:[UIImage imageNamed:@"buyPriceDown"] forState:UIControlStateNormal];
        [_pPlusPriceBtn setImage:[UIImage imageNamed:@"buyPriceUp"] forState:UIControlStateNormal];
        [_pMinusNumBtn setImage:[UIImage imageNamed:@"buyNumDown"] forState:UIControlStateNormal];
        [_pPlusNumBtn setImage:[UIImage imageNamed:@"buyNumUp"] forState:UIControlStateNormal];
    }else {
        [_pTradeBtn setTitle:@"卖出" forState:UIControlStateNormal];
        _pTradeBtn.backgroundColor = kMYHexToRGB(0x3399ff, 1);
        [_pMinusPriceBtn setImage:[UIImage imageNamed:@"sellPriceDown"] forState:UIControlStateNormal];
        [_pPlusPriceBtn setImage:[UIImage imageNamed:@"sellPriceUp"] forState:UIControlStateNormal];
        [_pMinusNumBtn setImage:[UIImage imageNamed:@"sellNumDown"] forState:UIControlStateNormal];
        [_pPlusNumBtn setImage:[UIImage imageNamed:@"sellNumUp"] forState:UIControlStateNormal];
    }
}

- (void)adjustOnClick:(UIButton *)btn
{
    NSInteger nTag = btn.tag;
    NSString *pPrice = _pPriceTextField.text;
    NSString *pNum = _pNumTextField.text;
    switch (nTag) {
        case 1:
            {
                CGFloat fPrice = [pPrice floatValue];
                fPrice -= 0.01;
                pPrice = [NSString stringWithFormat:@"%0.2f", fPrice];
                NSString *minPrice = [_pMinPriceLabel.text substringFromIndex:3];
                NSString *maxPrice = [_pMaxPriceLabel.text substringFromIndex:3];
                NSUInteger nMin = [minPrice floatValue]*100;
                NSUInteger nMax = [maxPrice floatValue]*100;
                NSUInteger nPrice = fPrice*100;
                if (nPrice == nMin || nPrice < nMin) {
                    _pMinusPriceBtn.enabled = NO;
                }
                if (nPrice < nMax) {
                    _pPlusPriceBtn.enabled = YES;
                }
            }
            break;
        case 2:
        {
            CGFloat fPrice = [pPrice floatValue];
            fPrice += 0.01;
            pPrice = [NSString stringWithFormat:@"%0.2f", fPrice];
            NSString *minPrice = [_pMinPriceLabel.text substringFromIndex:3];
            NSString *maxPrice = [_pMaxPriceLabel.text substringFromIndex:3];
            NSUInteger nMin = [minPrice floatValue]*100;
            NSUInteger nMax = [maxPrice floatValue]*100;
            NSUInteger nPrice = fPrice*100;
            if (nPrice > nMin) {
                _pMinusPriceBtn.enabled = YES;
            }
            if (nPrice == nMax || nPrice > nMax) {
                _pPlusPriceBtn.enabled = NO;
            }
        }
            break;
        case 3:
        {
            NSInteger nNum = [pNum integerValue];
            nNum -= 100;
            if (nNum < 0) {
                nNum = 0;
            }
            pNum = [NSString stringWithFormat:@"%ld", (long)nNum];
        }
            break;
        case 4:
        {
            NSInteger nNum = [pNum integerValue];
            nNum += 100;
            pNum = [NSString stringWithFormat:@"%ld", (long)nNum];
        }
            break;
            
        default:
            break;
    }
    if (![pPrice isEqual:@""]) {
        _pPriceTextField.text = pPrice;
    }
    if (![pNum isEqual:@""]) {
        _pNumTextField.text = pNum;
    }
}
- (void)tradeTypeOnClick
{
    if (_pTradeType.isSelected) {
        LogicRouterBlock block = [self.logicManager matchLogicBlock:kLogicRouterPeiziTradeType];
        if (block) {
            block(nil, @[_pTradeType, @(_pTempData.nModel_market)]);
        }
    }
}
- (void)tradeBtnOnClick
{
    NSArray *params = @[_pTradeType.currentTitle, _pTempData.model_name, _pTempData.model_code, @(_pTempData.nModel_market), _pPriceTextField.text, _pNumTextField.text, _pTradeBtn.currentTitle];
    
    LogicRouterBlock block = [self.logicManager matchLogicBlock:kLogicRouterPeiziBuySellAction];
    if (block) {
        block(nil, params);
    }
}

- (void)clearBothData
{
    _pCodeTextField.text = @"";
    _pCodeUpTextField.text = @"";
    _pNameLabel.text = @"";
    _pCodeUpTextField.hidden = _pNameLabel.hidden = YES;
    [self clearData];
}
- (void)clearData
{
    _isLoadingData = NO;
    _pNumTextField.placeholder = @"委托数量";
    _pTradeType.selected = NO;
    [_pTradeType setTitle:@"限价" forState:UIControlStateSelected];
    _pPriceTextField.text = @"";
    _pMaxPriceLabel.text = @"涨停";
    _pMinPriceLabel.text = @"跌停";
    _pNumTextField.text = @"";
    _pMinusNumBtn.enabled = _pPlusNumBtn.enabled = NO;
    _pMinusPriceBtn.enabled = _pPlusPriceBtn.enabled = NO;
    
    [_pWudangView clearData];
    
    LogicRouterBlock block = [self.logicManager matchLogicBlock:kLogicRouterPeiziCancelSubscribe];
    if (block) {
        block(nil, nil);
    }
}

- (void)textFieldChange:(NSNotification *)noti
{
    NSString *text = nil;
    if ([noti.object isEqual:_pCodeTextField]) {
        text = _pCodeTextField.text;
        if (text.length == 6) {
            LogicRouterBlock block = [self.logicManager matchLogicBlock:kLogicRouterPeiziCodeSearch];
            if (block) {
                block(nil, text);
            }
            [self endEditing:YES];
        }
    }
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([textField isEqual:_pCodeTextField] && !_pCodeUpTextField.isHidden) {
        [_pCodeUpTextField becomeFirstResponder];
        [_pCodeTextField resignFirstResponder];
        return NO;
    }
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([textField isEqual:_pCodeUpTextField]) {
        if ([string isEqual:@""]) {
            NSString *subStr = [textField.text substringToIndex:textField.text.length - 1];
            _pCodeUpTextField.text = _pNameLabel.text = @"";
            _pCodeUpTextField.hidden = _pNameLabel.hidden = YES;
            _pCodeTextField.text = subStr;
            [_pCodeTextField becomeFirstResponder];
            [_pCodeUpTextField resignFirstResponder];
            [self clearData];
            return NO;
        }else if (textField.text.length == 6 ) {
             return NO;
        }
    }

    return YES;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
